//
//  XDRegisterViewController.m
//  XDEducation
//
//  Created by apple on 2017/4/5.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDRegisterViewController.h"
#import "XDLoginHeaderView.h"
#import "XDLoginTextFieldCell.h"
#import "XDRegisterBtnCell.h"

@interface XDRegisterViewController ()<UITextFieldDelegate>
{
    NSString *_userName; /** 用户名 */
    NSString *_password; /** 密码 */
    NSString *_vCode;   /** /验证码*/
    NSString *_inCode;  /** 邀请码 */
}

/** 用户名textfield */
@property(nonatomic,strong) UITextField *userNameTextField;
/** 密码textfield */
@property(nonatomic,strong) UITextField *passwordTextField;
/** 验证码textfield */
@property(nonatomic,strong) UITextField *vCodeTextField;
/** 邀请码extfield */
@property(nonatomic,strong) UITextField *inCodeTextField;

@end

static NSString *const registerCellId = @"RegisterBtnCell";

@implementation XDRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTableView];
}




/**
 初始化tableView
*/
-(void)initTableView{
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.scrollEnabled = NO;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(returnKeyboard)];
    [self.tableView addGestureRecognizer:tap];
}



#pragma - mark tableView delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 5;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WeakSelf(weakself)
    
    
    switch (indexPath.row) {
        
        case 0:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"login_icon_user" title:@"帐    号:" textFieldPalceHolder:@"请输入您的手机号码" tableView:tableView];
            self.userNameTextField = cell.textField;
            self.userNameTextField.delegate = self;
            return cell;
        }
            break;
            
        case 1:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"login_icon_password" title:@"密    码:" textFieldPalceHolder:@"请输入密码" tableView:tableView];
            cell.hidePassword = YES;
            self.passwordTextField = cell.textField;
            self.passwordTextField.delegate = self;
            return cell;
        }
            break;
        case 2:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"register_icon_invitation_default" title:@"邀请码:" textFieldPalceHolder:@"请输入邀请码(可不填)" tableView:tableView];
            self.inCodeTextField = cell.textField;
            self.inCodeTextField.delegate = self;
            return cell;
        }
            break;
            
        case 3:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"register_icon_validation_default" title:@"验证码:" textFieldPalceHolder:@"请输入验证码" tableView:tableView];
            cell.isIdentityCodeType = YES;
            self.vCodeTextField = cell.textField;
            self.vCodeTextField.delegate = self;
            cell.identityCodeBlock = ^(){
                //发送验证码
                [weakself sendCode];
            };
            return cell;
        }
            break;
        case 4:{
            
            XDRegisterBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:registerCellId];
            if (!cell) {
                [tableView registerNib:[UINib nibWithNibName:@"XDRegisterBtnCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:registerCellId];
                cell = [tableView dequeueReusableCellWithIdentifier:registerCellId];
            }
            cell.registerBlock = ^(){
                //注册
                [weakself registerEvent];
            };
            return cell;
        }
            break;
            
        default:
            return nil;
            break;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //if(indexPath.row == 2) return 135 * ScaleHeight ;
    return 70 * ScaleHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    XDLoginHeaderView *headerView = [[XDLoginHeaderView alloc]init];
    headerView.isRegister = YES;
    //返回block
    WeakSelf(weakself)
    headerView.backBlock = ^(){
        
        [weakself dismissViewControllerAnimated:YES completion:nil];
    };

    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return (ScreenH/3 + 40 ) * ScaleHeight;
}

#pragma mark  -   处理事件

/**
 注册
 */
-(void)registerEvent{

    NSLog(@"%@  %@  %@",_userName,_password,_vCode);

    
    [self returnKeyboard];
    //判断有效手机号
    NSString *message = [LLTools valiMobile:_userName];
    if(message.length != 0){
        [MBProgressHUD showError:message];
        return;
    }
    
    //判断密码格式     6 - 15 密码
    if(_password.length < 6  ){
        [MBProgressHUD showError:@"密码格式不正确"];
        return;
    }
    
    //判断验证码
    if (_vCode.length!=6) {
        [MBProgressHUD showError:@"验证码输入错误"];
        return;
    }
    
    [MBProgressHUD showHUD];
    
    //  角色  rolecode     3是大人    4是小孩
    //  注册默认传3
    NSString *rolecode = @"3";
    
    NSString *url = [NSString stringWithFormat:@"user.do?action=add&phone=%@&rolecode=%@&verifycode=%@&password=%@",_userName,rolecode,_vCode,_password];
    
    //1，创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2,根据会话创建task
    NSURL *urL = [NSURL URLWithString:[BaseURL(url) stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //3,创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urL];
    //4,请求方法
    request.HTTPMethod = @"POST";
    
    //    //设置请求体
    //    NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
    //         //把拼接后的字符串转换为data，设置请求体
    //    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    
    //5.根据会话创建一个task（发送请求）
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *  data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"response:%@",dic);
            //注册成功啦
            
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                //主线程刷新界面
                [MBProgressHUD hideHUD];
                NSDictionary *dict = [dic objectForKey:@"data"];
                
                if ([[[dict objectForKey:@"code"] stringValue] isEqualToString:@"1000"])  {
                    //注册成功
                    [MBProgressHUD showSuccess:[dict objectForKey:@"msg"]];
                }else{
                    //注册失败
                    [MBProgressHUD showError:[dict objectForKey:@"msg"]];
                }
            });
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //主线程刷新界面
                NSLog(@"%@",error);
                
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"网络请求错误"];
            });
            
            
        }
        
    }];
    
    [dataTask resume];
    //此次注册接口有问题 不能用AFNetworking框架   只能用原生网络请求
    

}


/**
 发送验证码
 */
-(void)sendCode{
    
    [self returnKeyboard];
    //判断有效手机号
    NSString *message = [LLTools valiMobile:_userName];
    if(message.length != 0){
        [MBProgressHUD showError:message];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在发送验证码"];

    [XDHttpTool get:BaseURL(@"user.do?action=verifycode") params:@{@"phone":_userName} success:^(id responseObj) {
        
        NSLog(@"验证码 -- %@",responseObj);
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD showError:@"验证码发送失败"];
        NSLog(@"%@",error);
    }];
    
}


/**
 return 键盘
 */
-(void)returnKeyboard{

    [self.view endEditing:YES];
}

#pragma - mark  TextField 代理方法

//弹回键盘
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 150, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}

//在UITextField 编辑完成调用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    //赋值
    if(textField == self.userNameTextField){
        
        _userName = textField.text;
        
    }else if(textField == self.passwordTextField){
        
        _password = textField.text;
        
    }else if(textField == self.vCodeTextField){
    
        _vCode = textField.text;
        
    }else if(textField == self.inCodeTextField){
    
        _inCode = textField.text;
    }
    
    
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 150, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}

-(void)dealloc{
    
    NSLog(@"%s",__func__);
}

@end
